
<template>
    <div class="amapContent">
        <!-- 头部搜索框 -->
        <div class="amapSearchTop">
            <van-search
                v-model="searchValue"
                show-action
                shape="round"
                placeholder="请输入地名查看位置"
            >
            <!-- background="#4fc08d" -->
                <template #action>
                    <div @keyup.enter="geography(searchValue)" @click="geography(searchValue)">搜索</div>
                </template>
            </van-search>
        </div>
        <!-- 地图 -->
        <div ref="container" id="container"></div>
        <div class="locationBox" @click="location1">
            <img :src="locationImg" alt="">
        </div>
        <!-- 拉起 -->
        <van-floating-panel v-model:height="height" :anchors="anchors">
            <div class="amapBox">
                <div class="amapBoxTop">
                    <van-cell-group inset style="width: 100%;">
                        <van-field v-model="startAddress" left-icon="location" label="" placeholder="请输入起点" clearable style="color: #4594d5;" />
                        <van-field v-model="endAddress" left-icon="location" label="" placeholder="请输入终点" clearable style="color: #c63520;" />
                    </van-cell-group>
                    <div style="margin-right: 25px;" @click="contrary">
                        <SvgIcon width="60px" height="60px" name="exchangeBtn" color="#f5c3cb"></SvgIcon>
                    </div>
                </div>
                <div class="amapBoxMain">
                    <div class="amapBoxMainBtn" @click="search">
                        <span>查看路线</span>
                    </div>
                </div>
            </div>
        </van-floating-panel>
    </div>
</template>
    
<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showFailToast, showConfirmDialog } from 'vant'
import MapLoader from "@/utils/amap"
import useSettingStore from '@/store/modules/setting'
const settings = useSettingStore()

import locationImg from '@/assets/img/location.png'
import { set } from 'lodash'

const route = useRoute()
const router = useRouter()

const container = ref<HTMLElement | null>(null)

const anchors = [
    170,
    Math.round(0.4 * window.innerHeight),
    Math.round(0.6 * window.innerHeight),
]
const height = ref(anchors[0]);

const map = ref<any>(null);
const AMap = ref<any>(null)
const marker = ref<any>(null)
const searchValue = ref<string>('')
const startAddress = ref<string>('')
const endAddress = ref<string>('')

const geocoder = ref<any>(null)
const driving = ref<any>(null)
const geolocation = ref<any>(null)


// 当前经纬度坐标
const latitude = ref<any>(0)
const longitude = ref<any>(0)

const copy = (mes: string) => {
    var input = document.createElement('input') 
    input.value = mes 
    document.body.appendChild(input) 
    input.select() 
    document.execCommand('copy') 
    document.body.removeChild(input)
    showToast('复制成功')
}

const contrary = () => {
    const temp = startAddress.value
    startAddress.value = endAddress.value
    endAddress.value = temp
}

const markerImg = ref('')

const init = () => {
    settings.handlerLoadingShow(true)
    MapLoader().then((AMap: any) => {
        settings.handlerLoadingShow(false)
        AMap.value = AMap
        console.log('AMap.value', AMap.value)
        map.value = new AMap.value.Map('container', {
            // center: [116.3972282, 39.9096045],
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11,
        })
        // 缩放控件 罗盘控件
        map.value.plugin(["AMap.ToolBar", "AMap.ControlBar"], function () {
            const toolBar = new AMap.value.ToolBar({
                position: 'LT',
                visible: true,
            });
            const controlBar = new AMap.value.ControlBar();
            map.value.addControl(toolBar);
            map.value.addControl(controlBar);
        });
        // 设置点样式
        const wristbandIcon = new AMap.value.Icon({
            size: new AMap.value.Size(48, 48),
            image: markerImg.value,
            // imageOffset: new AMap.value.Pixel(-16, -32)
        })

        marker.value = new AMap.value.Marker({
            position: new AMap.value.LngLat(longitude.value, latitude.value), // 基点经纬度
            // content: markerImg.value,
            offset: new AMap.value.Pixel(-16, -35),
            icon: wristbandIcon,
        });

        // 点击获取经纬度并标记点位
        map.value.on('click', function(e) {
            const { lng, lat } = e.lnglat;
            handleMapClick(lng, lat);
            if (marker.value) {
                marker.value.setMap(null);
                map.value.remove([marker.value]);
                marker.value = null;
            }
            // 在地图上添加标记
            marker.value = new AMap.value.Marker({
                position: new AMap.value.LngLat(lng, lat), // 基点经纬度
                // content: markerImg.value,
                offset: new AMap.value.Pixel(-16, -35),
                icon: wristbandIcon,
            });
            map.value.setFitView();
            // marker.value.setMap(map.value);
            map.value.setCenter([lng, lat])
            map.value.add([marker.value])
            console.log('map.value', map.value)
        });

        // 逆地理编码示例
        AMap.plugin('AMap.Geocoder', () => { // 异步加载地理编码插件
            geocoder.value = new AMap.Geocoder({
                radius: 500, // 范围
                extensions: 'all' // 返回地址组成要素的类别，默认所有
            });
        });


        AMap.plugin('AMap.Geolocation', function() {
            geolocation.value = new AMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                timeout: 5000, // 设置定位超时时间，默认：无穷大
                offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                position: 'RB', //  定位按钮的排放位置,  RB表示右下
                panToLocation: true, //  定位成功后是否自动调整地图视野到定位点，默认：false
                getCityWhenFail: true, //  定位失败后是否自动获取城市信息，默认：false
            })
        });

        driving.value = new AMap.value.Driving({
            policy:AMap.DrivingPolicy.LEAST_TIME,
            map: map.value,
        })

    })
    .catch((e) => {
        console.log(e)
        showFailToast('地图加载失败')
    });
}

const handleMapClick = (lng: any, lat: any) => {
    console.log('点击位置坐标：', lng, lat);
    inverseGeography(lng, lat)
}

const geography = (str) => {
    if (str == '') {
        showToast('请输入内容')
        return
    }
    if (geocoder.value) {
        geocoder.value.getLocation(str, (status, result) => {
            if (status === 'complete' && result.geocodes.length) {
                // console.log('地理编码', result.geocodes)
                const geocode = result.geocodes[0];
                map.value.setCenter(geocode.location); // 将地图中心点设置为地名位置
                startAddress.value = result.geocodes[0].formattedAddress
                handleMapClick(result.geocodes[0]?.location.lng, result.geocodes[0]?.location.lat)
            } else {
                console.error('根据地名查询位置失败');
                showFailToast('查询地址失败')
            }
        });
    }
}

const inverseGeography = (lng: any,lat: any) => {
    if (geocoder.value) {
        // 根据经纬度来获取地址描述
        geocoder.value.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.regeocode) {
                console.log('地址信息：', result.regeocode.formattedAddress); // 打印地址描述
                startAddress.value = result.regeocode.formattedAddress
            } else {
                console.error('获取地址失败');
                showFailToast('获取地址失败')
            }
        });
    }
}

const location1 = () => {
    if ("geolocation" in navigator) { // 浏览器是否支持地理位置服务
            navigator.geolocation.getCurrentPosition((position) => {
                console.log(position.coords)
                longitude.value = position.coords.longitude;
                latitude.value = position.coords.latitude;
                if (latitude.value && longitude.value) {
                    handleMapClick(longitude.value, latitude.value)
                    map.value.setCenter([longitude.value, latitude.value])
                    marker.value.setPosition([longitude.value, latitude.value])
                }
            },
            (error) => {
                console.error("浏览器获取位置失败:", error.message);
                showFailToast('浏览器获取位置失败')
                location2()
            }
        );
    } else {
        console.error("Geolocation is not supported by this browser.");
        location2()
    }
}

const location2 = () => {
    geolocation.value.getCurrentPosition(function(status,result){
        if(status=='complete'){
            onComplete(result)
        } else {
            onError(result)
        }
    });
}

const onComplete = (data) => {
    // data是具体的定位信息
    longitude.value = data.position.lng;
    latitude.value = data.position.lat;
    if (latitude.value && longitude.value) {
        handleMapClick(longitude.value, latitude.value)
        map.value.setCenter([longitude.value, latitude.value])
        marker.value.setPosition([longitude.value, latitude.value])
    }
}

const onError = (data) =>  {
    // 定位出错
    console.error("高德地图获取位置失败:", data);
    showFailToast('高德地图获取位置失败')
    // handleMapClick(116.3972282, 39.9096045)
}

// 驾车路线查询
const search = () => {
    if (startAddress.value == '') {
        showToast('请输入起点')
        return
    }
    if (endAddress.value == '') {
        showToast('请输入终点')
        return
    }
    if (driving.value) {
        driving.value.search([
            {
                keyword: startAddress.value
            },
            {
                keyword: endAddress.value
            }
        ], function(status, data) {
            console.log('驾车路线查询', status);
            console.log('驾车路线查询成功', data);
            // result 即是对应的驾车导航方案，具体字段看官方文档说明。
            if (status === 'complete') {
                showToast('请稍后')
                setTimeout(() => {
                    driving.value.searchOnAMAP({
                        origin:data.origin,
                        destination:data.destination
                    }); // 开启驾车导航；如果只想展示路线规划结果，可以忽略此行代码。
                }, 2500)
            } else if (status === 'no_data') {
                showFailToast('附近没有找到可行数据')
            }
        })
    }
}

onMounted(() => {
    nextTick(() => {
        init()
    })
    // showConfirmDialog({
    //     title: '',
    //     message: '不支持通话的设备将无法进行拨打，继续使用请点击确认',
    // }).then(() => {
    //     return true
    // })
    // .catch(() => {
    //     // on cancel
    //     router.back()
    // })
})

</script>


<style lang="scss" scoped>
.amapContent {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    overflow: hidden;
    position: relative;
    // padding: 15px;
    .amapSearchTop {
        width: 100%;
        height: auto;
        min-height: 55px;
    }
    #container {
        width: 100%;
        height: calc(100vh - 55px - 160px);
        position: relative;
    }
    .locationBox {
        position: absolute;
        bottom: 40px;
        right: 0;
        width: 100px;
        height: auto;
        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
    .amapBox {
        width: 100%;
        min-height: 100px;
        height: auto;
        box-sizing: border-box;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;
        overflow: hidden;
        .amapBoxTop {
            width: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-evenly;
            overflow: hidden;
            :deep(.van-cell) {
                // background-color: transparent; // 透明背景
            }
            :deep(.van-field__control) {
                padding-left: 20px; /* 左边的边距 */
                // color: #00FFFF;
            }
            :deep(.van-field__control::placeholder) {
                padding-left: 10px; /* 左边的边距 */
                // color: #00FFFF;
            }
        }
        .amapBoxMain {
            width: 100%;
            height: auto;
            box-sizing: border-box;
            margin-top: 10px;
            // background-color: aquamarine;
            padding: 0 15px;
            .amapBoxMainBtn {
                width: 95%;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                background: #c33779;
                // border: 1px solid #666;
                border-radius: 16px;
                span {
                    color: #FFFFFF;
                    font-size: 14px;
                    font-weight: 700;
                }
            }
        }
    }
}
</style>